#!/usr/bin/env bash
# Author: mikhailnov
# License: GPLv3
# Requires: bash, lynx

set -efu

date="$(date +%s)"
# https://stackoverflow.com/a/13864829
[ -z "${TMPDIR+x}" ] && TMPDIR="/tmp/abf-mirror_${date}"
[ ! -d "$TMPDIR" ] && mkdir -p "$TMPDIR"

mirror="${mirror:-http://mirror.rosalab.ru}"
platform="${platform:-rosa2016.1}"
projects_list_file="${projects_list_file:-"${TMPDIR}/import_SRPM.list"}"
debug="${debug:-no}"
[ "$debug" != 'no' ] && set -x
repos="main contrib non-free restricted"
repotypes="release testing updates"

[ -f "$projects_list_file" ] && echo "${projects_list_file} already exists!" && return 1
[ -f "${projects_list_file}.tmp" ] && rm -f "${projects_list_file}.tmp"
while read -r repo; do
while read -r repotype; do
	DUMP="$(lynx -dump "${mirror}/rosa/${platform}/repository/SRPMS/${repo}/${repotype}/")"
	# verify that the dump is not empty
	echo "$DUMP" | grep -q ". ${mirror}/"
	SRPM_names_list="$(echo "$DUMP" | grep ". ${mirror}/" | awk -F '/' '{print $NF}' | rev | cut -d '-' -f 3- | rev)"
	# verify that it is not empty
	[ -n "$SRPM_names_list" ]
	echo "$SRPM_names_list" >> "${projects_list_file}.tmp"
done < <(echo "$repotypes" | tr "$IFS" "\n")
done < <(echo "$repos" | tr "$IFS" "\n")

cat "${projects_list_file}.tmp" | sort -u | sed '/^$/d' > "${projects_list_file}"
rm -f "${projects_list_file}.tmp"
echo "Saved to: ${projects_list_file}"
# export the real location of the result to allow sourcing this script and have it set as a variable
export projects_list_file

